import { DatePicker, Input, InputNumber } from '@/components/AntdProxy';
import CommonDrawer from '@/components/CommonDrawer';
import CommonTable from '@/components/CommonTable';
import { CrudFormLayout } from '@/components/Crud';
import {
  DriverSelect,
  LineSelect,
  VehicleSelect,
} from '@/components/CustomForm';
import { REQUIRED } from '@/constants/rules';
import request from '@/utils/request';
import { ClearOutlined, LikeOutlined, PlusOutlined } from '@ant-design/icons';
import { useAsyncEffect, useRequest } from 'ahooks';
import {
  Button,
  Form,
  message,
  Modal,
  Popconfirm,
  Select,
  Space,
  Typography,
} from 'antd';
import dayjs from 'dayjs';
import { unionBy } from 'es-toolkit/array';
import { useState } from 'react';
import QuickAdd from './QuickAdd';
import Suggest from './Suggest';

const Option = Select.Option;

const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType = 'text',
  record,
  index,
  children,
  formItemRender,
  formItemProps,
  ...restProps
}) => {
  const inputNode = formItemRender ? (
    formItemRender(record)
  ) : inputType === 'number' ? (
    <InputNumber size="small" />
  ) : (
    <Input size="small" />
  );
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{ margin: 0 }}
          initialValue={record[dataIndex]}
          {...formItemProps}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};

const Save = (props) => {
  const { record, onCancel, onOk } = props;
  const [editingKey, setEditingKey] = useState('');
  const [isNewAdd, setIsNewAdd] = useState(false);
  const [dataSource, setDataSource] = useState([]);
  const [quickAddOpen, setQuickAddOpen] = useState(false);
  const [suggestOpen, setSuggestOpen] = useState(false);
  const [form] = Form.useForm();
  const [tableEditForm] = Form.useForm();

  const { data: tasks, runAsync } = useRequest(
    (params) =>
      request({
        url: '/datas/line/task/detail',
        method: 'GET',
        params,
      }),
    {
      manual: true,
      onSuccess: (res) => {
        setDataSource(
          res.tasks.map((task, index) => {
            return {
              ...task,
              index: index + 1,
              key: new Date().getTime() + index,
            };
          }),
        );
      },
    },
  );

  useAsyncEffect(() => {
    if (record) {
      form.setFieldsValue({
        ...record,
        planDate: record.planDate ? dayjs(record.planDate) : undefined,
      });
      runAsync({ lineTaskId: record.lineTaskId });
    }
  }, [record]);

  const handleOk = async () => {
    const values = await form.validateFields();
    const url = record ? '/datas/line/task/update' : '/datas/line/task/add';
    const params = {
      ...values,
      planDate: values.planDate
        ? dayjs(values.planDate).format('YYYY-MM-DD')
        : '',
      tasks: dataSource.map((item) => {
        return {
          vehicleId: item.vehicleId,
          driverId: item.driverId,
          backhaul: item.backhaul,
        };
      }),
    };
    if (record) {
      params.lineTaskId = record?.lineTaskId;
      params.uploadType = record?.uploadType;
    }
    await request({
      url,
      method: 'POST',
      data: params,
    });
    message.success('操作成功');
    onOk?.();
  };

  const isEditing = (record) => {
    return record.key === editingKey;
  };
  const edit = (record) => {
    // 设置表单初始值，将license映射到vehicleId，realname映射到driverId
    tableEditForm.setFieldsValue({
      ...record,
    });
    setIsNewAdd(false);
    setEditingKey(record.key);
  };

  const cancel = (key) => {
    if (isNewAdd) {
      setDataSource(dataSource.filter((item) => item.key !== key));
    }
    setEditingKey('');
  };
  const save = async (key) => {
    try {
      await tableEditForm.validateFields();
      const row = await tableEditForm.getFieldsValue(true);

      const newData = [...dataSource];
      const index = newData.findIndex((item) => key === item.key);
      const item = newData[index];

      // 构建新的数据项
      const newItem = {
        ...item,
        ...row,
      };

      // 检查车牌号是否重复
      const isSameLicense = newData.find(
        (dataItem) =>
          dataItem.key !== key && dataItem.vehicleId === newItem.vehicleId,
      );
      if (isSameLicense) {
        message.error('该车辆已有计划!');
        return;
      }

      // 根据是否为新增和是否有record来决定处理方式
      newData.splice(index, 1, newItem);
      setDataSource(newData);

      setEditingKey('');
      tableEditForm.resetFields();
      tableEditForm.setFieldsValue({});
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };
  const deleteRow = (vehiclePlan) => {
    Modal.confirm({
      title: `确认删除该行?`,
      onOk: async () => {
        setDataSource(
          dataSource.filter((item) => item.key !== vehiclePlan.key),
        );
      },
    });
  };

  const addRow = async () => {
    // 如果有正在编辑的行，先保存它
    if (editingKey) {
      try {
        await save(editingKey);
      } catch (error) {
        // 如果保存失败，不继续添加新行
        console.log('保存当前编辑行失败:', error);
        return;
      }
    }

    const uuid = new Date().getTime();
    tableEditForm.resetFields();
    const defaultData = {
      index: dataSource.length + 1,
      key: uuid,
      groupName: '',
      groupId: null,
      license: '',
      vehicleId: null,
      realname: '',
      driverId: null,
      state: 1,
      backhaul: 0,
      distance: 0,
    };
    setDataSource((_old) => _old.concat({ ...defaultData }));
    setIsNewAdd(true);
    setEditingKey(uuid);
    setTimeout(() => {
      tableEditForm.setFieldsValue({
        ...defaultData,
      });
    }, 0);
  };

  const columns = [
    {
      align: 'center',
      title: '操作',
      fixed: 'left',
      width: 90,
      editable: false,
      render: (text, record) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Typography.Link
              onClick={() => save(record.key)}
              style={{ marginInlineEnd: 8 }}
            >
              保存
            </Typography.Link>
            <Popconfirm
              title="确认取消?"
              onConfirm={() => {
                cancel(record.key);
              }}
            >
              <a>取消</a>
            </Popconfirm>
          </span>
        ) : (
          <span>
            <Typography.Link
              disabled={editingKey !== ''}
              onClick={() => edit(record)}
              style={{ marginInlineEnd: 8 }}
            >
              编辑
            </Typography.Link>
            <Typography.Link onClick={() => deleteRow(record)}>
              删除
            </Typography.Link>
          </span>
        );
      },
    },
    {
      title: '序号',
      // dataIndex: 'index',
      width: 55,
      editable: false,
      render: (text, record, index) => index + 1,
    },
    {
      title: '组织',
      dataIndex: 'groupName',
      width: 280,
      editable: true,
      formItemRender: () => <Input disabled size="small" />,
    },
    {
      title: '车牌号',
      dataIndex: 'vehicleId',
      width: 130,
      editable: true,
      formItemProps: {
        rules: [{ required: true, message: '请选择车牌号' }],
      },
      render: (text, record) => record.license,
      formItemRender: (record) => {
        return (
          <VehicleSelect
            size="small"
            onChange={(val, option) => {
              if (dataSource.find((item) => item.vehicleId === val)) {
                message.error('该车辆已有计划!');
                return;
              }
              tableEditForm.setFieldsValue({
                license: option?.license,
                groupId: option?.groupId,
                groupName: option?.groupName,
              });
              try {
                const driver = JSON.parse(option.drivers)?.[0];
                if (driver) {
                  tableEditForm.setFieldsValue({
                    driverId: driver?.driverId,
                    realname: driver?.realname,
                  });
                }
              } catch (error) {}
            }}
          />
        );
      },
    },
    {
      title: '驾驶员',
      dataIndex: 'driverId',
      width: 150,
      editable: true,
      render: (text, record) => record.realname,
      formItemRender: (record) => (
        <DriverSelect
          size="small"
          onChange={(val, option) => {
            tableEditForm.setFieldsValue({
              realname: option?.realname,
            });
          }}
        />
      ),
    },
    {
      title: '回货',
      dataIndex: 'backhaul',
      render: (text) => {
        return {
          0: '否',
          1: '是',
        }[text];
      },
      editable: true,
      width: 80,
      formItemRender: () => {
        return (
          <Select
            size="small"
            options={[
              { label: '是', value: 1 },
              { label: '否', value: 0 },
            ]}
          />
        );
      },
    },
    // {
    //   title: '当前运营线路',
    //   dataIndex: 'lineName',
    //   width: 120,
    //   editable: false,
    // },
    // {
    //   title: '运营状态',
    //   dataIndex: 'state',
    //   width: 100,
    //   editable: false,
    //   render: (text) => {
    //     return text === 0 ? '停运' : '运营中';
    //   },
    // },
    // {
    //   title: '距离装货地距(km)',
    //   dataIndex: 'distance',
    //   width: 140,
    //   editable: false,
    // },
  ];

  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: 'text',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
        formItemRender: col.formItemRender,
        formItemProps: col.formItemProps,
      }),
    };
  });

  const lineId = Form.useWatch('lineId', form);
  return (
    <CommonDrawer
      title={record ? '编辑' : '新建'}
      open={true}
      onClose={onCancel}
      onOk={handleOk}
      afterOpenChange={(visible) => {
        if (!visible) {
          form.resetFields();
        }
      }}
      width={1000}
      destroyOnHidden
    >
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
        <Form form={form} layout="vertical">
          <CrudFormLayout itemMinWidth={250}>
            <Form.Item
              label="计划日期"
              name="planDate"
              rules={[REQUIRED]}
              initialValue={dayjs().add(1, 'day')}
            >
              <DatePicker placeholder="请选择日期" />
            </Form.Item>
            {/* <Form.Item></Form.Item> */}
            <Form.Item label="计划线路" name="lineId" rules={[REQUIRED]}>
              <LineSelect />
            </Form.Item>
            <Form.Item
              label="计划趟次"
              name="trips"
              rules={[REQUIRED]}
              initialValue={1}
            >
              <InputNumber min={0} precision={0} />
            </Form.Item>
            <Form.Item label="回货线路" name="backLineId">
              <LineSelect />
            </Form.Item>
            <Form.Item label="回货趟次" name="backTrips">
              <InputNumber min={0} precision={0} />
            </Form.Item>
          </CrudFormLayout>
          <Form.Item label="备注" name="remark">
            <Input.TextArea maxLength={150} />
          </Form.Item>
          <Space style={{ marginBottom: '8px' }}>
            <Button
              type="primary"
              size="small"
              icon={<LikeOutlined />}
              onClick={() => {
                form
                  .validateFields(['lineId', 'planDate', 'trips'])
                  .then(() => {
                    setSuggestOpen(true);
                  })
                  .catch(() => {
                    message.info('请先选择计划线路、计划日期和计划趟次');
                  });
              }}
            >
              排班推荐
            </Button>
            <Button
              type="primary"
              size="small"
              icon={<PlusOutlined />}
              onClick={addRow}
            >
              添加一行
            </Button>
            <Button
              type="primary"
              size="small"
              icon={<PlusOutlined />}
              onClick={() => {
                setQuickAddOpen(true);
              }}
            >
              快速添加
            </Button>
            {!record && (
              <Button
                size="small"
                icon={<ClearOutlined />}
                onClick={() => {
                  setDataSource([]);
                  tableEditForm.resetFields();
                  setEditingKey('');
                  setIsNewAdd(false);
                }}
              >
                清空
              </Button>
            )}
          </Space>
        </Form>
        <Form form={tableEditForm} component={false}>
          <div style={{ flex: 1, minHeight: 200 }}>
            <CommonTable
              components={{
                body: { cell: EditableCell },
              }}
              // scroll={{ x: 940 }}
              // bordered
              dataSource={dataSource}
              columns={mergedColumns}
              rowClassName="editable-row"
              pagination={false}
            />
          </div>
        </Form>
      </div>
      <QuickAdd
        lineId={lineId}
        open={quickAddOpen}
        onCancel={() => {
          setQuickAddOpen(false);
        }}
        onOk={(valueList) => {
          setDataSource((_old) => {
            const result = unionBy(_old, valueList, (item) => item.vehicleId);
            return result;
          });
          setQuickAddOpen(false);
        }}
      />
      <Suggest
        baseForm={form}
        open={suggestOpen}
        onCancel={() => {
          setSuggestOpen(false);
        }}
        onOk={(valueList) => {
          if (valueList?.length > 0) {
            setDataSource([...valueList]);
          }
          setSuggestOpen(false);
        }}
      />
    </CommonDrawer>
  );
};

export default Save;
